package com.boarsoft.dao.sharding.oceanbase.filter;

import java.sql.SQLException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

/**
 * 向DRUID添加filter，并移除已创建的真实连接
 */
@Configuration
public class DruidShardingFilterAutoConfig {
	@Autowired(required = false)
	private DruidDataSource druidDataSource;

	@PostConstruct
	public void addFilter() throws SQLException {
		// 清空初始化的物理连接，确保创建的都是代理连接
		for (int i = 0; i < druidDataSource.getInitialSize(); i++) {
			DruidPooledConnection connection = druidDataSource.getConnection();
			connection.getConnection().close();
		}
		this.druidDataSource.getProxyFilters().add(new DruidShardingFilter());
	}
}
